#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       binary_search.py
#       
#       Copyright 2010 zr.public@gmail.com
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

#todo
# add a check for any items in the array being a string i.e > "string"
# if string len > 1, check in sub array [0][4]

def binary_search(array = [1,2,3,4,5,6], desired_element = 5):
	
	array_size = len(array)
	current_element = 0
	middle = array_size / 2
	
	print "Your looking for " + str(desired_element)
	print "Your array is " + str(array)
	
	while(current_element != array_size):
		
		if(array[middle - 1] == desired_element):
			print "Desired Element is  " +  str(middle)
			return middle
			break
		
		if(desired_element > middle):
	
			current_element = middle
			while(1):
			
				if(current_element == array_size):
					
					print "Element not found"
					break
		

				if(array[current_element] == desired_element):
					
					print "Element Found at " + str(current_element)
					return current_element
					break
				current_element += 1
			
			
		if(desired_element < middle):
				
				
			while(1):

				if(current_element == middle):
					print "Element not found"
					break
					
				if(array[current_element] == desired_element):
					print "Element found at " + str(current_element)
					return current_element
					break
					
				current_element += 1
		


def main():
	
	binary_search([1,2,3,4,8,16,32],16) # > middle
	binary_search([1,2,3,4,8,16,32],2) # < middle ! broken!!
	binary_search([1,2,3,4,8,16,32],3) # == middle
	
	return 0

if __name__ == '__main__':
	main()
